using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using AjGenesisStudio.Properties;
using AjGenesisStudio.Tools;
using System.IO;

namespace AjGenesisStudio.Dialogs
{
    public partial class ExternalToolsDialog : Form
    {
        bool InEdit = false;
        BindingList<Tools.ExternalTool> tools;
        int currentIndex = -1;

        public ExternalToolsDialog()
        {
            InitializeComponent();
        }

        private void btnArguments_Click(object sender, EventArgs e)
        {
            Point p = this.PointToScreen(btnArguments.Location);
            p.X += btnArguments.Width;
            mnuArguments.Show(p);
        }

        private void btnDirectory_Click(object sender, EventArgs e)
        {
            Point p = this.PointToScreen(btnDirectory.Location);
            p.X += btnDirectory.Width;
            mnuDirectory.Show(p);
        }

        private void mnuArgProjectDir_Click(object sender, EventArgs e)
        {
            txtArguments.SelectedText = "$(ProjectDir)";
        }

        private void mnuArgFolder_Click(object sender, EventArgs e)
        {
            txtArguments.SelectedText = "$(ProjectFolder)";
        }

        private void mnuArgItemDir_Click(object sender, EventArgs e)
        {
            txtArguments.SelectedText = "$(ItemDir)";
        }

        private void mnuArgItemPath_Click(object sender, EventArgs e)
        {
            txtArguments.SelectedText = "$(ItemPath)";
        }

        private void mnuArgItemName_Click(object sender, EventArgs e)
        {
            txtArguments.SelectedText = "$(ItemFileName)";
        }

        private void mnuArgItemExt_Click(object sender, EventArgs e)
        {
            txtArguments.SelectedText = "$(ItemExt)";
        }

        private void mnuDirProject_Click(object sender, EventArgs e)
        {
            txtDirectory.SelectedText = "$(ProjectDir)";
        }

        private void mnuDirItem_Click(object sender, EventArgs e)
        {
            txtDirectory.SelectedText = "$(ItemDir)";
        }

        private void ExternalToolsDialog_Load(object sender, EventArgs e)
        {
            ListExternalTools();
        }

        private void ListExternalTools()
        {
            tools = new BindingList<Tools.ExternalTool>();
            
            ArrayList lst = Settings.Default.ExternalTools;
            if (lst == null) lst = new ArrayList();

            tools.Clear();
            lstContent.Items.Clear();

            foreach (object o in lst)
                tools.Add((Tools.ExternalTool)o);

            lstContent.DataSource = tools;
            lstContent.DisplayMember = "Title";
        }

        private void lstContent_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool val = (lstContent.SelectedIndex > -1);
            btnRemove.Enabled = val;
            btnMoveDown.Enabled = val;
            btnMoveUp.Enabled = val;

            if (val && (currentIndex != lstContent.SelectedIndex))
            {
                InEdit = false;
                EnableEdit(true, true);
                ShowValues((Tools.ExternalTool)lstContent.SelectedItem);
                currentIndex = lstContent.SelectedIndex;
                InEdit = true;
            }
        }

        private void EnableEdit(bool enabled, bool clear)
        {
            txtArguments.Enabled = enabled;
            txtCommand.Enabled = enabled;
            txtDirectory.Enabled = enabled;
            txtTitle.Enabled = enabled;
            btnArguments.Enabled = enabled;
            btnCommand.Enabled = enabled;
            btnDirectory.Enabled = enabled;
            chkUseOutput.Enabled = enabled;
            if (!enabled) InEdit = false;
            if (clear)
            {
                bool prevVal = InEdit;
                InEdit = false;
                txtArguments.Text = string.Empty;
                txtCommand.Text = string.Empty;
                txtDirectory.Text = string.Empty;
                txtTitle.Text = string.Empty;
                chkUseOutput.Checked = true;
                InEdit = prevVal;
            }
        }

        private void ShowValues(Tools.ExternalTool tool)
        {
            txtArguments.Text = tool.Arguments;
            txtCommand.Text = tool.Command;
            txtDirectory.Text = tool.WorkingDirectory;
            txtTitle.Text = tool.Title;
            chkUseOutput.Checked = tool.UseOuputWindow;
        }

        private Tools.ExternalTool GetSelectedTool()
        {
            return (Tools.ExternalTool)lstContent.SelectedItem;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            int number = 0;
            int max = 0;
            InEdit = false;

            Tools.ExternalTool tool = new Tools.ExternalTool();
            foreach (Tools.ExternalTool t in tools)
            {
                if (t.Title.StartsWith("[new tool "))
                    if (int.TryParse(t.Title.Substring(10, t.Title.Length - 11), out number))
                        if (number > max)
                            max = number;
            }
            max++;
            tool.Title = "[new tool " + max.ToString() + "]";
            tools.Add(tool);

            currentIndex = -1;
            lstContent.SelectedIndex = -1;
            lstContent.SelectedItem = tool;
            
            txtTitle.SelectAll();
            txtTitle.Focus();

            btnApply.Enabled = true;
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            tools.Remove((Tools.ExternalTool)lstContent.SelectedItem);
            lstContent.SelectedIndex = -1;
            EnableEdit(false, true);
            currentIndex = -1;
            //lstContent_SelectedIndexChanged(null, null);
            btnApply.Enabled = true;
        }

        private void btnMoveUp_Click(object sender, EventArgs e)
        {
            for (int i = 0; i <= tools.Count - 1; i++)
            {
                if ((lstContent.SelectedIndex == i) && (i > 0))
                {
                    ExternalTool t = tools[i];
                    tools.RemoveAt(i);
                    tools.Insert(i - 1, t);
                    lstContent.SetSelected(i - 1, true);
                }
            }
        }

        private void btnMoveDown_Click(object sender, EventArgs e)
        {
            for (int i = tools.Count - 1; i >= 0; i--)
            {
                if ((lstContent.SelectedIndex == i) && (i < tools.Count - 1))
                {
                    ExternalTool t = tools[i];
                    tools.RemoveAt(i);
                    tools.Insert(i + 1, t);
                    lstContent.SetSelected(i + 1, true);
                }
            }
        }

        private void txtTitle_TextChanged(object sender, EventArgs e)
        {
            if (InEdit) {
                GetSelectedTool().Title = txtTitle.Text;
                btnApply.Enabled = true;
            }
        }

        private void txtCommand_TextChanged(object sender, EventArgs e)
        {
            if (InEdit) {
                GetSelectedTool().Command = txtCommand.Text;
                btnApply.Enabled = true;
            }
        }

        private void txtArguments_TextChanged(object sender, EventArgs e)
        {
            if (InEdit) {
                GetSelectedTool().Arguments = txtArguments.Text;
                btnApply.Enabled = true;
            }
        }

        private void txtDirectory_TextChanged(object sender, EventArgs e)
        {
            if (InEdit) {
                GetSelectedTool().WorkingDirectory = txtDirectory.Text;
                btnApply.Enabled = true;
            }
        }

        private void chkUseOutput_CheckedChanged(object sender, EventArgs e)
        {
            if (InEdit) {
                GetSelectedTool().UseOuputWindow = chkUseOutput.Checked;
                btnApply.Enabled = true;
            }
        }

        private void btnCommand_Click(object sender, EventArgs e)
        {
            if (dlgOpen.ShowDialog() == DialogResult.OK) {
                txtCommand.Text = dlgOpen.FileName;
                btnApply.Enabled = true;
            }
        }

        private void txtTitle_Validating(object sender, CancelEventArgs e)
        {
            int cnt = 0;
            foreach (Tools.ExternalTool t in tools)
                if (t.Title == txtTitle.Text)
                    cnt++;
            if (cnt > 1)
            {
                MessageBox.Show("There is another tool with the same title.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
        }

        private void txtCommand_Validating(object sender, CancelEventArgs e)
        {
            string value = txtCommand.Text;
            if (string.IsNullOrEmpty(value))
            {
                if (!File.Exists(value))
                {
                    MessageBox.Show("Wrong command, the file doesn't exists.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }
            }
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            ApplySettings();
            btnApply.Enabled = false;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            ApplySettings();
        }

        private void ApplySettings()
        {
            if (Settings.Default.ExternalTools == null)
                Settings.Default.ExternalTools = new ArrayList();

            Settings.Default.ExternalTools.Clear();
            Settings.Default.ExternalTools.AddRange(tools);
            
            Global.Instance.MainForm.FillExternalTools();
        }
    }
}